package demo3;

import java.util.Arrays;

public class MyArrayList implements IList{
    public int[] elem;
    public int useSize;

    public MyArrayList(){
         elem = new int[10];
    }

    @Override
    public void add(int data) {
        if(isFull()){
            grow();
        }
        elem[useSize] = data;
        useSize++;
    }

    private void grow(){
        elem = Arrays.copyOf(elem,2 * elem.length);
    }

    @Override
    public void add(int pos, int data) {
        if(pos < 0 || pos > useSize){
            throw new PosOutOfException("pos位置不合法");
        }
        if(isFull()){
            grow();
        }
        for(int i = useSize-1; i >= pos; i--){
            elem[i+1] = elem[i];
        }
        elem[pos] = data;
        useSize++;

    }

    @Override
    public boolean contains(int toFind) {

        for (int i = 0; i < useSize - 1; i++) {
            if(elem[i] == toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {

        for (int i = 0; i < useSize-1; i++) {
            if(elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        if(isEmpty()){
            System.out.println("elem为空");
        }
        
        if(pos < 0 || pos > useSize){
            throw new PosOutOfException("pos位置不合法==");
        }
        
        return elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        if(pos < 0 || pos > useSize){
            throw new PosOutOfException("pos位置不合法==");
        }
        elem[pos] = value;
        
    }

    @Override
    public void remove(int toRemove) {
        int index = indexOf(toRemove);
        for (int i = index; i < useSize - 1; i++) {
            elem[i] = elem[i +1];
        }
        useSize--;
    }

    @Override
    public int size() {
        
        return useSize;
    }

    @Override
    public void clear() {
        useSize = 0;
    }

    @Override
    public void display() {
        for (int e = 0; e < useSize; e++) {
            System.out.print(elem[e] + " ");
        }
        System.out.println();
    }

    @Override
    public boolean isFull() {
        return (this.elem.length == useSize);
    }

    @Override
    public boolean isEmpty() {
        return (useSize == 0);
    }
}
